package com.mybatis.Util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static String CONFIG_FILE = "mybatis-config.xml";
	private static SqlSessionFactory sessionFactory;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    /**
	* 静态初始化块，完成创建唯一的SqlSessionFactory对象
	*/
	static {
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		try {
			sessionFactory = builder.build(Resources
					.getResourceAsStream(CONFIG_FILE));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    /**
	* 线程安全地创建SqlSession对象
	* @return SqlSession对象
	*/
	public static SqlSession getSqlSession() {
		SqlSession session = threadLocal.get();
		if (session == null) {
			session = sessionFactory.openSession(true);
			threadLocal.set(session);
		}
		return session;
	}
	public static void closeSqlSession() {
		SqlSession session = threadLocal.get();
		if (session != null) {
			session.close();
			threadLocal.set(null);
		}
	}
	/**
	*  获得Dao接口实现类
	* @param clazz Dao接口类型
	* @return Dao接口实现类
	*/
	public static <T> T getMapper(Class<T> clazz){
		return getSqlSession().getMapper(clazz);
	}
}

